// pages/confirmOrder/confirmOrder.js
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _token:'',
    cartList:[],//选中商品
    imgpath: '',//图片路径

    pagetype: '',//页面类型
    address_info: '',//地址
    show_status: '',//显示添加地址

    zongjia:'',//总价
    totalprice:'',//合计

    coupon_list:[],//优惠券列表
    couponInfo:'',//优惠券信息
    coupon_id:'' //使用的优惠券id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //console.info(options)
    var that = this;
    //获取登陆状态
    var _key = wx.getStorageSync("token");
    var imgpath = app.globalData.imgsPath;
   
   

    that.setData({
      _token: _key,
    
      imgpath: imgpath
    })

    var _pirce = wx.getStorageSync("totalprice");
    if (_pirce != "") {
      that.setData({
        totalprice: _pirce,
        zongjia: _pirce
      })
    }
    if (options.pagesType == 'selected') {
      var addressInfo = wx.getStorageSync("addressInfo");
      that.setData({
        address_info: addressInfo,
        show_status: false
      })
    } else {
      //获取地址列表
      wx.request({
        url: app.globalData.httpsPath + '/user/address/index',
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          token: _key,
        },
        //请求后台数据成功  
        success: function (res) {
          //console.info(res.data.data.data)
          var _list = res.data.data.data;
          var addressInfo;

          if (_list.length > 0) {
            for (var i = 0; i < _list.length; i++) {
              if (_list[i].is_default == 1) {
                //console.info(_list[i])
                addressInfo = _list[i];
                if (addressInfo.province == null) {
                  addressInfo.province = "";
                }
                if (addressInfo.city == null) {
                  addressInfo.city = "";
                }
                if (addressInfo.zone == null) {
                  addressInfo.zone = "";
                }
                that.setData({
                  address_info: addressInfo,
                  show_status: false
                })
              }
            }

          } else {
            that.setData({
              show_status: true
            })
          }

        }
      })
    }

    //获取优惠券
    that.getCouponList()
    // 购物车信息
    that.getCartList()
    
    setTimeout(function () {
      var couponid = options.couponId;
      var _couponlist = that.data.coupon_list
      if (couponid != "") {
        _couponlist.forEach(function (i, index) {
          if (i.coupon.id == couponid) {

            var heji = parseInt(_pirce);
            var overPrice = heji - i.coupon.reduce;
            
            that.setData({
              couponInfo:i,
              totalprice: overPrice,
              coupon_id:couponid
            })
          }
        })
      }
    }, 800)
    
    
  },
  //添加收货地址
  addnewAddress:function(){
    wx.navigateTo({
      url: '../addNewaddress/addNewaddress?type=new&pagesType=selected&fromPage=confirmOrder',
    })
  },
  //选择地址
  selectAddress: function () {
    wx.navigateTo({
      url: '../addressList/addressList?pagesType=selected',
    })

  },
  //选择优惠券
  selectCoupon:function(){
    wx.navigateTo({
      url: '../couponList/couponList?pagesType=selected',
    })
  },
  //获取购物车列表
  getCartList: function () {
    var that = this;
    var _key = that.data._token;
    var ids  = wx.getStorageSync('cartItems') 
    wx.request({
      url: app.globalData.httpsPath + '/cart/list',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        token: _key,
        ids: ids
      },
      //请求后台数据成功  
      success: function (res) {
        var _cartlist = res.data.data;
       
     
        console.info(_cartlist);
        that.setData({
          cartList: _cartlist
        })
      }
    })
  },

  getCouponList:function(){
    var that = this;
    var _key = that.data._token;
    var _pirce = wx.getStorageSync("totalprice");
    var heji = parseInt(_pirce);
    //获取优惠券
    wx.request({
      url: app.globalData.httpsPath + '/user/coupon/index',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        token: _key,
      },
      //请求后台数据成功  
      success: function (res) {
        var _coupon_list = res.data.data.data;
        //console.info(_coupon_list)
        var fulllist = [];
        for (let i = 0; i < _coupon_list.length; i++) {
          if (heji >= _coupon_list[i].coupon.full) {
            fulllist.push(_coupon_list[i]);
          }
        }
        console.info(fulllist)
        that.setData({
          coupon_list: fulllist
        })

      }
    })
  },
  //提交订单
  subPay:function(e){
   
    var that = this;
    var form_id = e.detail.formId;  
    var user_id = wx.getStorageInfoSync('agent_id');
    var _address_id = that.data.address_info.id;
    var _list = that.data.cartList
    var idlist = [];
    for (let i = 0; i < _list.length; i++) {
      idlist.push(_list[i].id);
    }
    var strIds = idlist.join(",");
    if (that.data.address_info == ""){
      wx.showToast({
        icon: "none",
        title: '请选择收货地址'
      })
      return ;
    }
    wx.request({
      url: app.globalData.httpsPath + '/order/add',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        token: that.data._token,
        cart_ids: strIds,
        address_id: _address_id,
        form_id:form_id,
        coupon_id: that.data.coupon_id
       
      },
      //请求后台数据成功  
      success: function (res) {
        console.info(res);
        if (res.data.status == true) {
          var data = res.data.data;
          wx.requestPayment({
            timeStamp: data.timeStamp.toString(),
            nonceStr:data.nonceStr,
            package:data.package,
            signType: 'MD5',
            paySign: data.paySign,
            success(rs) {
              console.info(rs);
              wx.showToast({
                title: '支付成功',
                icon: 'succes',
                duration: 1500,
                mask: true
              })
              wx.removeStorageSync("cartItems");
              wx.removeStorageSync('totalprice');
            
              wx.reLaunch({
                url: '../personalCenter/personalCenter',
              })
             },
            fail(rs) { }
          })
        }
      }
    })
   
  },
  
})